package com.gaofans.nrpc.server.handler;

import com.gaofans.nrpc.common.context.ContextRequest;
import com.gaofans.nrpc.common.context.ContextResponse;
import com.gaofans.nrpc.common.context.SelectableExecutor;
import com.gaofans.nrpc.common.protocol.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author GaoFans
 */
@ChannelHandler.Sharable
public class ContextBindHandler extends MessageToMessageCodec<RpcRequest, ContextResponse> {

    private final static Logger LOGGER = LoggerFactory.getLogger(ContextBindHandler.class);

    private final SelectableExecutor chooser;

    public ContextBindHandler(SelectableExecutor chooser) {
        this.chooser = chooser;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ContextResponse contextResponse, List<Object> list) {
        list.add(contextResponse.getResponse());
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, RpcRequest request, List<Object> list) {
        LOGGER.debug("收到 request {}",request.getSequenceId());
        ContextRequest contextRequest = new ContextRequest.ContextRequestBuilder(request)
                .executor(chooser.select(request.getSequenceId()))
                .build();
        list.add(contextRequest);
    }
}
